from json import tool
from django.shortcuts import render, HttpResponse
from .models import apinfo, threatdb
from django.http import HttpResponseRedirect, HttpResponse
from django.http import JsonResponse
from django.db import connection
import json
import requests
from django.urls import reverse
from django.core import serializers
import socket,datetime
from .tools.timelong import time_long
# Create your views here.

def retime():
    now = datetime.date.today()
    return now

def transday(today):
    tday = str(today)[:4]+str(today)[5:7]+str(today)[8:]
    return tday

# 威胁情报查询
def threat(request):
    return render(request, 'threat.html')

#判断数据库中是否已有记录
def dbexist(parm):
    cursor = connection.cursor()
    cursor.execute("select ip from threat_threatdb  where domains=%s",[parm])
    dbres = cursor.fetchall()
    return dbres

# ajax调用微步api
def threat_info(request):
    if request.is_ajax():
        #if request.method == 'POST':
        host = request.POST['ip']
        ip = socket.gethostbyname(host)
        url = "https://api.threatbook.cn/v3/scene/ip_reputation"
        apikey1 = "149b6ca99dcb458c8cff50237e5bcd21efcc7f2c26564349a4b2c1bfdc990ad2" #186
        apikey2 = "40c0a9de684b4cbbbbe2f27b2cb86d79922cdb1554a5446a8cb3d4a2f95b8b9a" #176
        resource = ip
        lang = "zh"
    query = {
        "apikey": apikey2,
        "resource": resource,
        "lang": lang
    }
    currentkey = query['apikey'] #currentkey作为api计数方法参数
    dbres = dbexist(host)
    if len(dbres) != 0: #有记录先从库里查数据
        print('有记录') 
        lastime = threatdb.objects.filter(domains=host).values('search_time')[0].get('search_time') #库中该记录的时间值
        #last_tday = transday(lastime)
        nowtime = retime() #当前时间
        #now_tday = transday(nowtime)
        #timediff = int(now_tday)-int(last_tday) #时间差int型
        timediff = time_long(lastime, nowtime, type="day")
        print(timediff)
        if timediff <=7: #距离上次查询时间小于7天则直接返回数据库查询记录
            print('开始本地查询')
            is_malicious = threatdb.objects.filter(domains=host).values('is_malicious')[0].get('is_malicious')
            carrier = threatdb.objects.filter(domains=host).values('carrier')[0].get('carrier')
            country = threatdb.objects.filter(domains=host).values('country')[0].get('country')
            province = threatdb.objects.filter(domains=host).values('province')[0].get('province')
            city = threatdb.objects.filter(domains=host).values('city')[0].get('city')
            severity = threatdb.objects.filter(domains=host).values('severity')[0].get('severity')
            update_time = threatdb.objects.filter(domains=host).values('update_time')[0].get('update_time')
            resarray = [is_malicious,carrier,country,province,city,severity,update_time]
        else: #距离上次查询时间大于7天则调用api查询
            print('开始请求api,更新库中数据')
            response = requests.get(url, query)
            if response.status_code == 200:
                print('请求数据成功，当日请求次数+1')
                #apicount()
            resp = response.json() #将请求的数据转换为json格式
            if resp['data'][resource]['is_malicious'] == True:
                is_malicious = "是"
            else:
                is_malicious = "否"
            carrier = resp['data'][resource]['basic']['carrier']
            country = resp['data'][resource]['basic']['location']['country']
            province = resp['data'][resource]['basic']['location']['province']
            city = resp['data'][resource]['basic']['location']['city']
            severity = resp['data'][resource]['severity']
            update_time = resp['data'][resource]['update_time']
            #查看库中被查询域名的ip字段值
            dbip = threatdb.objects.filter(domains=host).values('ip')[0].get('ip')
            if dbip == resource: #如果IP不变化，不更新数据库记录
                print('数据一致，无需更新')
            else: #如果IP有变化，更新数据库记录
                print('需更新数据')
                threatdb.objects.filter(domains=host).update(ip=resource)
                threatdb.objects.filter(domains=host).update(is_malicious=is_malicious)
                threatdb.objects.filter(domains=host).update(carrier=carrier)
                threatdb.objects.filter(domains=host).update(country=country)
                threatdb.objects.filter(domains=host).update(province=province)
                threatdb.objects.filter(domains=host).update(city=city)
                threatdb.objects.filter(domains=host).update(severity=severity)
                threatdb.objects.filter(domains=host).update(update_time=update_time)
                threatdb.objects.filter(domains=host).update(search_time=retime())
                print('更新数据成功')
            resarray = [is_malicious,carrier,country,province,city,severity,update_time]
    else: #如果没有记录则调用api查询后数据入库
        print('数据库无记录，开始请求api')
        response = requests.get(url, query)
        if response.status_code == 200:
            print('请求数据成功，当日请求次数+1')
        resp = response.json() #将请求的数据转换为json格式
        if resp['data'][resource]['is_malicious'] == True:
            is_malicious = "是"
        else:
            is_malicious = "否"
        carrier = resp['data'][resource]['basic']['carrier']
        country = resp['data'][resource]['basic']['location']['country']
        province = resp['data'][resource]['basic']['location']['province']
        city = resp['data'][resource]['basic']['location']['city']
        severity = resp['data'][resource]['severity']
        update_time = resp['data'][resource]['update_time']
        #返回resarray数组
        resarray = [is_malicious,carrier,country,province,city,severity,update_time]
        thinfo = threatdb()
        thinfo.domains = host
        thinfo.ip = resource
        thinfo.is_malicious = is_malicious
        thinfo.carrier = carrier
        thinfo.country = country
        thinfo.province = province
        thinfo.city = city
        thinfo.severity = severity
        thinfo.update_time = update_time
        thinfo.ti_source = "微步"
        thinfo.save()
        print('数据成功入库')
    return JsonResponse(resarray,safe=False,json_dumps_params={'ensure_ascii':False})

    
# api设置页面
def setapi(request):
    return render(request, 'setapi.html')


# 查询当前所有api
def searchapi(request):
    apilist = apinfo.objects.all().order_by('id')
    return render(request, 'setapi.html', {'apilist': apilist})


# ajax查询当前所有api
def ajax_query_api(request):
    if request.is_ajax():
        # api_list = apinfo.objects.all().values('apitype', 'apikey')
        api_list = apinfo.objects.all().order_by('id')
        api = serializers.serialize("json", api_list)
        api = json.loads(api)
        data = []
        for i in range(len(api)):
            data.append(api[i]['fields'])
            finalData = {
                'api': data
            }
        # data = {
        #    'api': api
        # }
        # return JsonResponse(data)
        return JsonResponse(finalData)


# 作接口用范例
def viewapi(request):
    api_list = apinfo.objects.all().order_by('id')
    api = serializers.serialize("json", api_list)
    api = json.loads(api)
    data = []
    for i in range(len(api)):
        data.append(api[i]['fields'])
        finalData = {
            'api': data
        }
    return HttpResponse(json.dumps(finalData))
    # api_list = apinfo.objects.all().values('apitype','apikey')
    # api_list = apinfo.objects.all().order_by('id')
    # ret = serializers.serialize("json", api_list)
    # return HttpResponse(ret)

# 添加api
def addapi(request):
    if request.method == 'POST':
        temp_apitype = request.POST['apitype']
        temp_apikey = request.POST['apikey']

    temp_api = apinfo(
        apitype=temp_apitype,
        apikey=temp_apikey,
    )
    temp_api.save()
    return HttpResponseRedirect(reverse('setapi'))